<template>
  <div class="wrapper">
    <div class="box">
      <el-form
      :model = 'loginForm'
      :rules="formRules"
      label-width="80px"
      ref = 'formElement'
      >
        <h1 class="ltitle">登录</h1>
        <!-- 用户名 -->
        <el-form-item  label="用户名" name='userName' prop="username">
          <el-input
           placeholder="请输入用户名"
           prefix-icon="el-icon-user"
           v-model="loginForm.username"
          ></el-input>
        </el-form-item>
        <!-- 密码框 -->
        <el-form-item  label="密码" name = 'password' prop = "password">
          <el-input
          type="password"
          placeholder="请输入密码"
          prefix-icon="el-icon-user"
          v-model="loginForm.password"
          ></el-input>
        </el-form-item>
        <!-- 点击登录 -->
        <el-form-item class="doubleButton">
          <el-button type="primary" size="medium" @click="login">登录</el-button>
          <el-button type="info" size="medium" @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@api'
export default {
  data () {
    return {
      // 表单绑定数据
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 表单验证规则
      formRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置表单内容
    resetForm () {
      this.$refs.formElement.resetFields()
    },
    // 验证表单
    login () {
      this.$refs.formElement.validate(async (valid) => {
        // valid 为一个布尔值，表示表单是否验证通过
        if (!valid) return
        const { data: res } = await login(this.loginForm)
        if (res.meta.status !== 200 && res.meta.status !== '') {
          this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'warning'
          })
        } else {
          // 将token存入sessionStorage
          window.sessionStorage.setItem('token', res.data.token)
          this.$message({
            showClose: true,
            message: res.meta.msg,
            type: 'success',
            onClose: () => {
              this.$router.push('/admin')
            }
          })
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.doubleButton{
  margin-left: 150px;
}
h1{
  text-align: center;
  margin-bottom: 30px;
}
.wrapper{
  height: 100%;
  background:#1a9988 no-repeat;
  background-size: 100%  100%;
}
.box {
  width:400px;
  height: 300px;
  padding: 30px;
  background-color: #fff;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
}
</style>
